package cn.com.infcn.monitor.task.jvm.impl;

import java.io.IOException;
import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;

import javax.management.MBeanServerConnection;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.infcn.monitor.bean.IFCResponseBean;
import cn.com.infcn.monitor.jvm.bean.IFCJVMClassLoading;
import cn.com.infcn.monitor.task.impl.BaseTask;
import cn.com.infcn.monitor.util.IFCBeanUtils;
import cn.com.infcn.monitor.util.IFCMinitorConstanst;

/**
 * 用于 Java 虚拟机的类加载系统的管理接口。
 * 
 * @author jjs
 *
 */
public class JVMClassLoadingTask extends BaseTask {

	private final static Logger logger = LoggerFactory.getLogger(JVMClassLoadingTask.class);

	public JVMClassLoadingTask(IoSession session, Object message) {
		super(session, message);
	}

	@Override
	public void execute() throws Exception {

		IFCResponseBean result = jvmClassLoading();
		sendResponse(result);
	}

	public IFCResponseBean jvmClassLoading() {
		IFCResponseBean result = new IFCResponseBean();
		IFCJVMClassLoading ifcClassLoading = null;

		MBeanServerConnection mbs = null;
		try {
			// 获取MBeanServerConnection
			mbs = MBeanServerConnectionFactory.getInstance(IFCMinitorConstanst.JMXURL);
		} catch (IOException e) {
			logger.error("jmx.url 连接异常！" + e.getMessage());
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
			result.setResponseMsg("jmx.url 连接异常！");
			return result;
		}

		try {
			ClassLoadingMXBean classLoadingMXBean = ManagementFactory.newPlatformMXBeanProxy(mbs,
					ManagementFactory.CLASS_LOADING_MXBEAN_NAME, ClassLoadingMXBean.class);

			ifcClassLoading = new IFCJVMClassLoading();

			IFCBeanUtils.copyProperties(classLoadingMXBean, ifcClassLoading);

			result.setResult(ifcClassLoading);
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_OK);
		} catch (Exception e) {
			logger.error(e.getMessage());
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
			result.setResponseMsg(e.getMessage());
		}

		return result;
	}

	public static void main(String[] args) {
		JVMClassLoadingTask task = new JVMClassLoadingTask(null, null);
		IFCResponseBean result = task.jvmClassLoading();
		IFCJVMClassLoading ifcClassLoading = (IFCJVMClassLoading) result.getResult();

		System.out.println(ifcClassLoading.getLoadedClassCount());
		System.out.println(ifcClassLoading.getTotalLoadedClassCount());
		System.out.println(ifcClassLoading.getUnloadedClassCount());
		System.out.println(ifcClassLoading.getIsVerbose());
	}

}
